/**
 * idea
 *
 * @author songhuan <iphper@yeah.net>
 * @version $Id: idea-1.0.0.js 1 2010-08-10 14:40:00Z $
 */
idea = {
	/**
	 * 判断浏览器类型
	 * @return string
	 */
    browserType: function() {
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('opera') != -1 && opera.version()) {
            return "opera";
        }
        //Mozilla Firefox
        else if ((navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3)) {
            return "moz";
        }
        //IE，遨游，搜狗
        else if (userAgent.indexOf('msie') != -1 && userAgent.substr(userAgent.indexOf('msie') + 5, 3)) {
            return "ie";
        }
        else if (userAgent.indexOf('mac') != -1) {
            return "mac";
        }

        return undefined;
    },

    /**
	 * 通过ID名，获取元素对象
	 * @param string|object element
	 * @return object
	 */
    id: function(element) {
        return typeof(element) == 'object' ? element : document.getElementById(element);
    },

    /**
	 * 清除字符串左边空格
	 * @param string E
	 * @return string
	 */
    ltrim: function(E) {
        return (E||"").replace(/^\s+/g,"");
    },

    /**
	 * 清除字符串右边空格
	 * @param string E
	 * @return string
	 */
    rtrim: function(E) {
        return (E||"").replace(/\s+$/g,"");
    },

    /**
	 * 清除字符串两边空格
	 * @param string E
	 * @return string
	 */
    trim: function(E) {
        return (E||"").replace(/^\s+|\s+$/g,"");
    },

    /**
	 * 计算字符串长度
	 * @param string E
	 * @param string charset
	 * @return integer
	 */
    mb_strlen: function(E, charset) {
        var len = 0;
        var Elen = E.length;
        for (var i = 0; i < Elen; i++) {
            len += E.charCodeAt(i) < 0 || E.charCodeAt(i) > 255 ? (charset == "utf-8" ? 3 : 2) : 1;
        }

        return len;
    },

    /**
	 * 切割字符串
	 * @param string E
	 * @param integer maxlen
	 * @param string charset
	 * @return string
	 */
    mb_cutstr: function(E, maxlen, charset) {
        var len = 0;
        var ret = "";
        var Elen = E.length;
        for (var i = 0; i < Elen; i++) {
            len += E.charCodeAt(i) < 0 || E.charCodeAt(i) > 255 ? (charset == "utf-8" ? 3 : 2) : 1;
            if (len > maxlen) {
                break;
            }

            ret += E.substr(i, 1);
        }

        return ret;
    },

    /**
	 * 字符串首字母大写
	 * @param string E
	 * @return string
	 */
    ucfirst: function(E) {
        return E.substr(0, 1).toUpperCase() + E.substr(1).toLowerCase();
    },

    /**
	 * 判断字符串是否在数组中
	 * @param string needle
	 * @param array haystack
	 * @return boolean
	 */
    in_array: function(needle, haystack) {
        if (typeof needle == 'string' || typeof needle == 'number') {
            for (var i in haystack) {
                if (haystack[i] == needle) {
                    return true;
                }
            }
        }

        return false;
    },

    /**
	 * 将数组连接成字符串
	 * @param string glue
	 * @param array pieces
	 * @return string
	 */
    join: function(glue, pieces) {
    	var ret = "";
        for (var i in pieces) {
            ret += pieces[i];
            if (i < pieces.length - 1) {
            	ret += glue;
            }
        }

        return ret;
    },

    /**
	 * 判断是否是邮箱格式
	 * @param string E
	 * @return boolean
	 */
    isMail: function(E) {
        var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ ;
        if (E == "" || !pattern.test(E)) {
            return false;
        }

        return true;
    },

    /**
	 * 判断是否是整数
	 * @param integer E
	 * @return boolean
	 */
    isInt: function(E) {
    	var pattern = /^[0-9]+$/ ;
    	if (E == "" || !pattern.test(E)) {
            return false;
        }

    	return true;
    },

    /**
	 * 判断是否是闰年
	 * @param integer year
	 * @return boolean
	 */
    isLeapYear: function(year) {
         return (0 == year%4 && ((year%100 != 0) || (year%400 == 0)));
    },

    /**
	 * 验证生日的年份是否合理，年份区间：1901 - 当前年
	 * @param integer year
	 * @return integer
	 */
    validYear: function(year) {
        if (year == "") return 0;
        if ( /^[0-9]+$/.test(year) && year <= new Date().getFullYear() && year > 0 && parseInt(year) >= 1901) return 1;
        return -1;
    },

    /**
	 * 验证生日的月份是否合理
	 * @param integer month
	 * @return integer
	 */
    validMonth: function(month) {
        if (month == "") return 0;
        if ( /^[0-9]+$/.test(month) && month <= 12 && month > 0) return 1;
        return -1;
    },

    /**
	 * 验证生日的日期是否合理
	 * @param integer year
	 * @param integer month
	 * @param integer day
	 * @return integer
	 */
    validDay: function(year, month, day) {
        if (day == "") return 0;
        maxday = 31;
        if (month != null || month != "") {
            switch (parseInt(month)) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    maxday = 31; break;
                case 2:
                    if(isLeapYear(year)) maxday = 29;
                    else maxday = 28;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    maxday = 30; break;
                default:
                    maxday=31;
            }
        }
        if ( /^[0-9]+$/.test(day) && day <= maxday && day > 0) return 1;
        return -1;
    },

    /**
     * 静态页面获取参数
     * @return array
     */
    queryString: function() {
    	var _GET = [];

        var uri = window.location.href;
        var strpos = uri.indexOf("?") + 1;
        if (strpos == 0) {
            return _GET;
        }

        var uri = uri.substr(strpos);
        if (uri.length == 0) {
            return _GET;
        }

        var tmp = [];
        if (uri.indexOf("&") == -1) {
            tmp = uri.split("=");
            _GET[tmp[0]] = tmp[1];
            return _GET;
        }

        var uris = uri.split("&");
        for (var i in uris) {
        	tmp = uris[i].split("=");
            _GET[tmp[0]] = tmp[1];
        }

        return _GET;
    },

    /**
     * 获取Cookie
     * @param string name
     * @return string
     */
    getCookie: function(name) {
        var cookies = document.cookie.split("; ");
        for (var i in cookies) {
            var crumbs = cookies[i].split("=");
            if (name == crumbs[0]) {
                return decodeURIComponent(crumbs[1]);
            }
        }

        return null;
    },

    /**
     * 设置Cookie
     * @param string name
     * @param string value
     * @param integer expires
     * @return void
     */
    setCookie: function(name, value, expires) {
        var cookies = name + "=" + encodeURIComponent(value);
        if (expires != null) {
            cookies += "; expires=" + expires;
        }

        document.cookie = cookies;
    },

    /**
     * 删除Cookie
     * @param string name
     * @return void
     */
    removeCookie: function(name) {
        document.cookie = name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
    },

    /**
     * Ajax
     * @param json p
     * p = {type: "GET"|"POST", url: "", data: "", dataType: "TEXT|JSON", async: true|false, success: function(ret) {}}
     * @return mixed
     */
    ajax: function(p) {
        var xhrObj = false;

        try {
            xhrObj = new XMLHttpRequest(); // Firefox IE8和非IE内核浏览器
        }
        catch (e) {
            var progid = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; // IE5.5 IE6 IE7内核
            for (var i in progid) {
                try {
                    xhrObj = new ActiveXObject(progid[i]);
                }
                catch (e) {
                    continue;
                }
                break;
            }
        }

        if (p.type != undefined) {
        	p.type = p.type.toUpperCase(); 
        }
        if (p.type != "POST") {
            p.type = "GET";
            p.url.indexOf("?") == -1 ? p.url += "?" + p.data : "";
            p.data = null;
        }

        p.async != false ? p.async = true : "";
        xhrObj.open(p.type, p.url, p.async);
        if ("POST" == p.type) {
            xhrObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        xhrObj.send(p.data);

        if (p.dataType != undefined) {
            p.dataType = p.dataType.toUpperCase();
        }
        p.dataType != "JSON" ? p.dataType = "TEXT" : "";

        xhrObj.onreadystatechange = function() {
            /**
             * readyState 值
             * 2 已经发送数据了，但是还没接收到反馈
             * 3 收到反馈了，反馈描述数据正在发送的过程中
             * 4 反馈描述数据已经被接收完毕
             */
            if (xhrObj.readyState == 4) {
                if (xhrObj.status == 200) {
                	var data = xhrObj.responseText;
                	if (p.dataType == "JSON") {
                		eval("data = " + data + ";");
                	}
                	
                    return p.success(data);
                }
            }
        }
    },

    /**
	 * 通过input类型和名称获取所有的input元素
	 * @param string type
	 * @param string name
	 * @return array
	 */
    getInputs: function(type, name) {
    	var ret = [];
    	var i = 0;
    	var inputs = document.getElementsByTagName("input");
    	for (var j in inputs) {
    		if (!idea.isInt(j)) {
    			continue;
    		}

    		if (inputs[j].type != type || inputs[j].name != name) {
    			continue;
    		}

    		ret[i++] = inputs[j];
    	}

    	return ret;
    },

    /**
	 * 通过input类型和名称获取一个input元素
	 * @param string type
	 * @param string name
	 * @return object
	 */
    getInput: function(type, name) {
    	var inputs = idea.getInputs(type, name);
    	if (inputs.length > 0) {
    		return inputs[0];
    	}

    	return undefined;
    },

    /**
	 * 通过input类型和名称获取所有被选中的input元素，适用于radio和checkbox
	 * @param string type
	 * @param string name
	 * @return array
	 */
    getChkedInputs: function(type, name) {
    	var ret = [];
    	var i = 0;
    	var inputs = idea.getInputs(type, name);
    	for (var j in inputs) {
    		if (!idea.isInt(j)) {
    			continue;
    		}

    		if (inputs[j].checked) {
    			ret[i++] = inputs[j];
    		}
    	}

    	return ret;
    },

    /**
	 * 通过input类型和名称获取所有未被选中的input元素，适用于radio和checkbox
	 * @param string type
	 * @param string name
	 * @return array
	 */
    getUnchkedInputs: function(type, name) {
    	var ret = [];
    	var i = 0;
    	var inputs = idea.getInputs(type, name);
    	for (var j in inputs) {
    		if (!idea.isInt(j)) {
    			continue;
    		}

    		if (!inputs[j].checked) {
    			ret[i++] = inputs[j];
    		}
    	}

    	return ret;
    },

    /**
	 * 判断是否所有的input元素的都被选中，适用于radio和checkbox
	 * @param string type
	 * @param string name
	 * @return boolean
	 */
    isInputsChked: function(type, name) {
    	var inputs = idea.getUnchkedInputs(type, name);
    	return (inputs.length > 0) ? false : true;
    },
    
    /**
	 * 改变所有的input元素的选中状态，适用于radio和checkbox
	 * @param string type
	 * @param string name
	 * @param boolean chked
	 * @return void
	 */
    chgInputsChked: function(type, name, chked) {
    	var inputs = idea.getInputs(type, name);
    	for (var i in inputs) {
    		inputs[i].checked = chked;
    	}
    },
    
    /**
	 * 获取所有被选中的input元素的值，适用于radio和checkbox
	 * @param string type
	 * @param string name
	 * @return array
	 */
    getChkedInputsVal: function(type, name) {
    	var ret = [];
    	var inputs = idea.getChkedInputs(type, name);
    	for (var i in inputs) {
    		ret[i] = inputs[i].value;
    	}
    	
    	return ret;
    }
}
